package in.muton.edushare.panels.upload.thin;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.pages.common.EdusharePanel;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.MultiFileUploadField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.util.lang.Bytes;

import com.edushare.common.constants.ApplicationConstants;
import com.edushare.common.dao.FileDirectoriesDAO;
import com.edushare.common.dao.FileUploadInfoDAO;
import com.edushare.common.util.URLUtils;
import com.edushare.common.util.UploadUtils;
import com.edushare.common.vo.FileDirectories;
import com.edushare.common.vo.FileUploadInfo;
import com.edushare.common.vo.FilesUploaded;
import com.edushare.common.vo.Users;

/**
 * TODO: CLEAN THIS UP!!!!
 * @author Naishe
 *
 */
public class MultiUpload extends EdusharePanel {

	private static final long serialVersionUID = 5162322882628104856L;
	private static final Log log = LogFactory.getLog(MultiUpload.class);
	
	public MultiUpload(String id, IModel<String> tempDirId){
		super(id);
		add(new FeedbackPanel("feedback"));
		add(new MultiUploadForm("simpleUpload", tempDirId));
	}
	
	
	/** Form */
	
	public class MultiUploadForm extends Form<Void>{
		
		private static final long serialVersionUID = -4513719763556520888L;
		private final Collection<FileUpload> uploads = new ArrayList<FileUpload>();
		private final IModel<String> tempDirId;
		
		public Collection<FileUpload> getUploads(){
            return uploads;
        }
		
		public MultiUploadForm(String id, IModel<String> tempDirId) {
			super(id);
			this.tempDirId = tempDirId;
			setMultiPart(true);
			
			MultiFileUploadField multiUploadField = 
				new MultiFileUploadField(
						"fileInput", 
						new PropertyModel<Collection<FileUpload>>(this, "uploads"),
						ApplicationConstants.MAX_FILES_UPLOADABLE);
			
			add(multiUploadField);
			setMaxSize(Bytes.megabytes(10));
		}
		
		
		@Override
		protected void onSubmit() {
			Iterator<FileUpload> it = uploads.iterator();
			while(it.hasNext()){
				final FileUpload upload = it.next();
				processFile(upload);
			}
		}

		private void processFile(FileUpload upload) {
			FileUploadInfo fuvo = registerFileUploadToDb(upload);
			FileDirectories fileDir = new FileDirectoriesDAO(EduShareSession.get().getSessionORMInterface())
										.getOrCreateTempDirectory(tempDirId.getObject());
			
			String finalFileName = getFileName(upload, fuvo);
			String uploadDirectory = UploadUtils.getMediaUploadPath();
			File storageFile = new File(uploadDirectory,finalFileName);
			boolean processedSuccessfully = true;
			
			try {
				storageFile.createNewFile();
				upload.writeTo(storageFile);
			} catch (IOException e) {
				log.fatal("ERROR WHILE CREATING / WRITTING FILE TO DISK!", e);
				e.printStackTrace();
				warn("Error while uploading.");
			}
			
			fuvo.setUploadStatus(FileUploadInfo.UPLOAD_STATUS_PREPROCESS);
			fuvo.setAbsoluteFilePath(uploadDirectory+"/"+finalFileName);
			fuvo.setFilePath(UploadUtils.getRelativeUploadPath(uploadDirectory+"/"+finalFileName));
			new FileUploadInfoDAO(EduShareSession.get().getSessionORMInterface()).saveFileUploadInfo(fuvo);
			
//			HttpServletRequest req = ((WebRequest)RequestCycle.get().getRequest()).getHttpServletRequest();
//			UploadProcessInfo info = (UploadProcessInfo)UploadProcessWebRequest.getUploadInfo(req);
			
			if(processedSuccessfully){
//				info.setProcessingStatus(UploadProcessInfo.PROCESSING_ENDED);
				fuvo.setUploadStatus(FileUploadInfo.UPLOAD_STATUS_POSTPROCESS);
				updateStorageDirectory(fuvo, fileDir);
				info("Upload completed.");
			}else{
//				info.setProcessingStatus(UploadProcessInfo.PROCESSING_FAILED);
				fuvo.setUploadStatus(FileUploadInfo.UPLOAD_STATUS_PROCESSING_FAILED);
			}
			new FileUploadInfoDAO(EduShareSession.get().getSessionORMInterface()).saveFileUploadInfo(fuvo);
			
			
			
		}
		
		private FileUploadInfo registerFileUploadToDb(FileUpload fileUpload) {
			FileUploadInfo fuvo = new FileUploadInfo();
			fuvo.setFileOrigName(fileUpload.getClientFileName());
			fuvo.setUploadStatus(FileUploadInfo.UPLOAD_STATUS_PREUPLOAD);
			fuvo.setUploadTimestamp(new Date(System.currentTimeMillis()));
			new FileUploadInfoDAO(EduShareSession.get().getSessionORMInterface()).createFileUploadInfo(fuvo);
			return fuvo;
		}
		
		private void updateStorageDirectory(FileUploadInfo fuvo, FileDirectories fd) {
			
			
			Users uploader  = EduShareSession.get().getLoggedInUser();
			FilesUploaded fuploaded = new FilesUploaded();
			fuploaded.setFileOrigName(fuvo.getFileOrigName());
			fuploaded.setFileRelativePath(fuvo.getFilePath());
//			fuploaded.setPermissionType(fd.getPermissionType());
			fuploaded.setUploader(uploader);
			fuploaded.setUploadTimestamp(new Date());
			fuploaded.setFileDirectory(fd);
		}
		
		private String getFileName(FileUpload fileUpload, FileUploadInfo fuvo){
			String origFileName = fileUpload.getClientFileName();
			String proposedFileName = origFileName.substring(0, origFileName.lastIndexOf('.'));//use originally uploaded fileName
			String fileExt = origFileName.substring(origFileName.lastIndexOf('.'));
			String finalFileName = URLUtils.escapeSplChars(proposedFileName+"_"+ fuvo.getFileUploadId())+fileExt;
			return finalFileName;
		}
		
		
	}
	
	
}
